﻿using System;
using System.Linq;
using System.Threading.Tasks;
using K9Nano.Dependency;
using K9Nano.Domain;

namespace K9Nano.MultiTenancy
{
    /// <summary>
    /// 读取租户信息
    /// !!! 因需要在DbContext.OnModelCreating中读取TenantId用于构建Global Query Filter，不能直接使用DbContext
    /// </summary>
    public class TenantStore : ITenantStore, ISingletonDependency
    {
        private readonly ITenantCache _cache;

        public TenantStore(ITenantCache cache)
        {
            _cache = cache;
        }

        public TenantInfo Find(Guid tenantId)
        {
            var name = _cache.Get(tenantId);
            return string.IsNullOrEmpty(name) ? null : new TenantInfo(tenantId, name);
        }

        public TenantInfo Find(string tenancyName)
        {
            var id = _cache.Get(tenancyName);
            return id == default ? new TenantInfo(id, tenancyName) : null;
        }

        public ValueTask<TenantInfo> FindAsync(Guid tenantId)
        {
            var tenant = Find(tenantId);
            return new ValueTask<TenantInfo>(tenant);
        }

        public ValueTask<TenantInfo> FindAsync(string tenancyName)
        {
            var tenant = Find(tenancyName);
            return new ValueTask<TenantInfo>(tenant);
        }
    }
}